<template>
  <div class="personal-center-container">
    <el-card class="personal-card">
      <div class="card-header">
        <h2 class="title">个人中心</h2>
      </div>
      
      <el-tabs v-model="activeTab" class="personal-tabs">
        <!-- 个人信息标签页 -->
        <el-tab-pane label="个人信息" name="info">
          <div class="user-profile">
            <div class="avatar-section">
              <div class="avatar-container">
                <el-avatar :size="100" :src="userInfo.img || defaultAvatar"></el-avatar>
                <div class="avatar-upload">
                  <el-upload
                    class="avatar-uploader"
                    action="http://localhost:80/api/myself/updateAvatar"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                    :data="{ userId: userInfo.userId }"
                    name="file"
                  >
                    <el-button type="primary" size="small" class="upload-btn">更换头像</el-button>
                  </el-upload>
                </div>
              </div>
            </div>
            
            <div class="info-section">
              <el-form :model="userInfo" label-width="100px" class="user-form">
                <el-form-item label="用户名">
                  <el-input v-model="userInfo.account" disabled></el-input>
                </el-form-item>
                <el-form-item label="姓名">
                  <el-input v-model="userInfo.name"></el-input>
                </el-form-item>
                <el-form-item label="手机号码">
                  <el-input v-model="userInfo.phone"></el-input>
                </el-form-item>
                <el-form-item label="邮箱">
                  <el-input v-model="userInfo.email"></el-input>
                </el-form-item>
                <el-form-item label="性别">
                  <el-radio-group v-model="userInfo.sex">
                    <el-radio :label="'0'">男</el-radio>
                    <el-radio :label="'1'">女</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" @click="updateUserInfo">保存修改</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </el-tab-pane>
        
        <!-- 修改密码标签页 -->
        <el-tab-pane label="修改密码" name="password">
          <div class="password-section">
            <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="120px" class="password-form">
              <el-form-item label="新密码" prop="newPassword">
                <el-input v-model="passwordForm.newPassword" type="password" show-password></el-input>
              </el-form-item>
              <el-form-item label="确认新密码" prop="confirmPassword">
                <el-input v-model="passwordForm.confirmPassword" type="password" show-password></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="updatePassword">修改密码</el-button>
                <el-button @click="resetPasswordForm">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>

      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useUserStore } from '@/stores/userStore';
import {update,updatepassword} from '@/api/person.js';

const userStore = useUserStore()

// 获取用户信息
const user = userStore.currentUser

// 当前激活的标签页
const activeTab = ref('info')

// 用户信息
const userInfo = reactive({

})

// 密码表单
const passwordFormRef = ref(null)
const passwordForm = reactive({

  newPassword: '',
  confirmPassword: ''
})

// 密码表单验证规则
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (passwordForm.confirmPassword !== '') {
      passwordFormRef.value.validateField('confirmPassword')
    }
    callback()
  }
}

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, validator: validatePass, trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validatePass2, trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ]
}


// 更新用户信息
const updateUserInfo = () => {

  update(userInfo).then(res=>{
    if (res.code === 200) {
      ElMessage.success('用户信息更新成功')
      userStore.loginSuccess(userInfo) // 更新用户信息到全局状态
      
    } else {
      ElMessage.error(res.message || '用户信息更新失败')
    }
  }).catch(error => {
    console.error('更新用户信息失败:', error)
    ElMessage.error('更新用户信息失败，请稍后再试')

    
    
  })
}

// 更新密码
const updatePassword = async () => {
  // 验证表单
  await passwordFormRef.value.validate()
  // 检查新密码和确认密码是否一致
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    ElMessage.error('新密码和确认密码不一致')
    return
  }else{
    userInfo.password = passwordForm.newPassword
      updatepassword(userInfo).then(res => {
    if (res.code === 200) {
      ElMessage.success('密码修改成功，请重新登录')
      userStore.logout()
      window.location.href = '/login'
    } else {
      ElMessage.error(res.message || '密码修改失败')
    }
  }).catch(error => {
    console.error('更新密码失败:', error)
    ElMessage.error('更新密码失败，请稍后再试')
 
  })

  }
  
}

// 重置密码表单
const resetPasswordForm = () => {
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields()
  }
}

// 头像上传前的验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2


  if (!isJPG && !isPNG) {
    ElMessage.error('头像只能是JPG或PNG格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过2MB!')
    return false
  }
  return true
}

// 头像上传成功的回调
const handleAvatarSuccess = (response, file) => {
  if (response.code === 200) {
    console.log(response)
    userInfo.img = response.data

    ElMessage.success('头像更新成功')
  } else {
    ElMessage.error(response.message || '头像上传失败')
  }
  

}
// 组件挂载时获取数据
onMounted(() => {

    Object.assign(userInfo, user);
    console.log('userInfo:', userInfo);

  // getUserInfo();
  // getSecurityLogs();


})
</script>

<style scoped>
.personal-center-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.personal-card {
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.card-header {
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

.title {
  margin: 0;
  font-size: 20px;
  color: #303133;
  font-weight: 600;
}

.personal-tabs {
  padding: 20px;
}

.user-profile {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

@media (min-width: 768px) {
  .user-profile {
    flex-direction: row;
  }
  
  .avatar-section {
    width: 30%;
  }
  
  .info-section {
    width: 70%;
  }
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.el-avatar {
  border: 4px solid #f0f2f5;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.el-avatar:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.avatar-upload {
  margin-top: 10px;
}

.upload-btn {
  border-radius: 20px;
  padding: 8px 16px;
}

.info-section {
  padding: 20px;
}

.user-form {
  max-width: 600px;
}

.password-section {
  padding: 20px;
}

.password-form {
  max-width: 500px;
  margin: 0 auto;
}

.security-section {
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}

/* 响应式调整 */
@media (max-width: 767px) {
  .personal-center-container {
    padding: 10px;
  }
  
  .personal-card {
    border-radius: 0;
    box-shadow: none;
  }
  
  .personal-tabs {
    padding: 10px;
  }
  
  .avatar-section,
  .info-section,
  .password-section,
  .security-section {
    padding: 10px;
  }
}
</style>